<template>
  <div class="app-container">
    <div>
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <el-tab-pane label="国家级" name="first">
          <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="100px">
            <el-form-item label="数据编号" prop="version">
              <el-input v-model="queryParams.version" placeholder="请输入数据编号" />
            </el-form-item>
            <el-form-item label="数据范围" prop="range">
              <el-select v-model="queryParams.provinceId" placeholder="请选择省" @change="chooseProvince" clearable>
                <el-option key="全国" label="全国" value="全国"></el-option>
                <el-option v-for="item in provinceData" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
              <el-select v-model="queryParams.cityId" placeholder="请选择市" @change="chooseCity" :disabled="queryParams.provinceId=='全国'" clearable>
                <el-option key="全部" label="全部" value="全部"></el-option>
                <el-option v-for="item in cityData" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
              <el-select v-model="queryParams.countyId" placeholder="请选择区/县" :disabled="queryParams.provinceId=='全国' || queryParams.cityId=='全部'" clearable>
                <el-option key="全部" label="全部" value="全部"></el-option>
                <el-option v-for="item in areaData" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery">查询</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="省级" name="second">
          <el-form :model="queryParams" ref="queryRef1" :inline="true" label-width="100px">
            <el-form-item label="数据编号" prop="version">
              <el-input v-model="queryParams.version" placeholder="请输入数据编号" />
            </el-form-item>
            <el-form-item label="数据范围" prop="range">
              <el-select v-model="queryParams.provinceId" placeholder="请选择省" @change="chooseProvince" clearable>
                <el-option key="全国" label="全国" value="全国"></el-option>
                <el-option v-for="item in provinceData" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
              <el-select v-model="queryParams.cityId" placeholder="请选择市" @change="chooseCity" :disabled="queryParams.provinceId=='全国'" clearable>
                <el-option key="全部" label="全部" value="全部"></el-option>
                <el-option v-for="item in cityData" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
              <el-select v-model="queryParams.countyId" placeholder="请选择区/县" :disabled="queryParams.provinceId=='全国' || queryParams.cityId=='全部'" clearable>
                <el-option key="全部" label="全部" value="全部"></el-option>
                <el-option v-for="item in areaData" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery">查询</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-col :span="1.5">
            <el-button type="primary" @click="handleUpload" v-if="isAdmin || activeName=='second'">
              <svg-icon class-name="upload-icon" icon-class="upload" /><span style="margin-left:10px">上传</span>
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" @click="handleDownloads" :disabled="multiple">
              <svg-icon class-name="download-icon" icon-class="download" /><span style="margin-left:10px">下载</span>
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" icon="Delete" :disabled="multiple" @click="handleDelete"
                       v-if="isAdmin || activeName=='second'">删除</el-button>
          </el-col>
        </el-col>
      </el-row>
      <!--版本列表-->
      <el-table v-loading="loading" border :data="dataList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="数据编号" align="center" prop="version" />
        <el-table-column label="省" align="center" prop="province" width="250" />
        <el-table-column label="市" align="center" prop="city" width="250" />
        <el-table-column label="区县" align="center" prop="county" width="250" />
        <el-table-column label="上传时间" align="center" prop="createTime" width="250" />
        <el-table-column label="上传人" align="center" prop="createUserName" width="250" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button type="text" @click="handleRemark(scope.row)">备注</el-button>
            <el-button type="text" @click="handleDownloadsById(scope.row)">下载</el-button>
            <el-button type="text" @click="handleDeleteById(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination :total="total"  v-show="total > 0" v-model:page="queryParams.page" v-model:limit="queryParams.rows"
                  @pagination="getList" />
      <!--上传工作空间-->
      <el-dialog title="上传" v-model="openDialog" width="800px" top="200px" append-to-body :close-on-click-modal="false">
        <el-form ref="uploadRef" label-width="120px" :model="form" :rules="rules">
          <el-form-item label="数据范围" prop="provinceId" style="margin-top:20px;">
            <el-select v-model="form.provinceId" placeholder="请选择省" @change="chooseFormProvince" clearable>
              <el-option key="全国" label="全国" value="全国"></el-option>
              <el-option v-for="item in provinceFormData" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
            <el-select v-model="form.cityId" placeholder="请选择市" @change="chooseFormCity" :disabled="form.provinceId=='全国'" clearable>
              <el-option key="全部" label="全部" value="全部"></el-option>
              <el-option v-for="item in cityFormData" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
            <el-select v-model="form.countyId" placeholder="请选择区/县" @change="chooseFormArea" :disabled="form.provinceId=='全国' || form.cityId=='全部'" clearable>
              <el-option key="全部" label="全部" value="全部"></el-option>
              <el-option v-for="item in areaFormData" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="超图工作空间"  prop="attachIds">
            <FileUpload :action="uploadFileUrl" :limit="2" ref="fileUpload" v-model="form.fileList" :fileSize="500" :fileType='["udbx", "smwu"]' />
          </el-form-item>
          <el-form-item label="数据源名称" prop="datasource">
            <el-input v-model="form.datasource" placeholder="请输入数据源名称"  clearable />
          </el-form-item>
          <el-form-item label="网络数据集名称" prop="dataset">
            <el-input v-model="form.dataset" placeholder="请输入网络数据集名称"  clearable />
          </el-form-item>
          <el-form-item label="">
            <el-link @click="handleDownloadHelp">
              <span style="color:red">（怎样获得工作空间文件、数据源名称和数据集名称？）</span>
            </el-link>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" placeholder="请输入备注" type="textarea" :rows="5" clearable />
          </el-form-item>
          <el-form-item label="注意事项：">
            <el-row>
              1、仅支持超图桌面端软件生成的工作空间文件；
            </el-row>
            <el-row>
              2、数据源名称、网络数据集名称要与工作空间文件中的名称保持一致。
            </el-row>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="fileSubmitForm">确 定</el-button>
            <el-button @click="openDialog = false">取 消</el-button>
          </div>
        </template>
      </el-dialog>
      <!--查看备注-->
      <el-dialog title="查看备注" v-model="openRemark" width="800px" top="200px" append-to-body>
        <el-form ref="remarkRef" label-width="50px" :model="remarkForm">
          <el-form-item label="备注" prop="remark" style="margin-top:20px;">
            <el-input v-model="remarkForm.remark" placeholder="" type="textarea" :rows="5" disabled />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="openRemark = false">关 闭</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup name="networkdataset">
import FileUpload from "./FileUpload/index.vue"
import { getNetworkVersionList,getPermission,newWorkspaceNetworkVersion,deleteNetworkanalystVersion } from "@/api/security/networkdataset.js"
import { getProvince, getChildArea } from "@/api/system/division";
import { useRoute } from "vue-router";

const { proxy } = getCurrentInstance();
const uploadFileUrl = ref(
    import.meta.env.VITE_APP_BASE_API + "/attachment/uploadSmwuFile"
); // 上传的文件服务器地址
const activeName = ref("first");
const isAdmin = ref(false);
const dataList = ref([]);
const loading = ref(false);
const total = ref(0);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const provinceData = ref([]); //省
const cityData = ref([]); //市
const areaData = ref([]); //区、县
const openDialog = ref(false);
const provinceFormData = ref([]);//表单省
const cityFormData = ref([]);//表单市
const areaFormData = ref([]);//表单区、县
const openRemark = ref(false);

const router = useRouter();
const route = useRoute();
const data = reactive({
  queryParams: {
    page: 1,
    rows: 10,
    provinceId: '',
    cityId: '',
    countyId: '',
    version: '',
    type: '0',//0国家级 1省级
  },
  form: {
    provinceId: '',
    cityId: '',
    countyId: '',
    province: '',
    city: '',
    county: '',
    fileList:[],
    datasource:'',
    dataset:'',
    attachIds:'',
    remark:'',
    type: '0',//0国家级 1省级
  },
  rules: {
    provinceId: [{ required: true, message: "省不能为空", trigger: "blur" }],
    datasource: [{ required: true, message: "数据源不能为空", trigger: "blur" }],
    dataset: [{ required: true, message: "网络数据集不能为空", trigger: "blur" }],
    attachIds: [{ required: true, message: "应上传1个.smwu文件和1个.udbx文件", trigger: "blur" }],
  },
  remarkForm:{}
});
const { queryParams, form,rules,remarkForm } = toRefs(data);

/*切换标签页*/
function handleClick(tab, event) {
  resetQuery();
}

function handleQuery(){
  //查询数据列表
  getList();
}

function resetQuery(){
  proxy.resetForm("queryRef");
  proxy.resetForm("queryRef1");
  queryParams.value.provinceId = '';
  queryParams.value.cityId = '';
  queryParams.value.countyId = '';
  queryParams.value.page = 1;
  if (activeName.value == "first") {
    queryParams.value.type = "0";//国家级
  } else {
    queryParams.value.type = "1";//省级
  }
  //查询数据列表
  getList();
}

/** 查询数据列表 */
function getList() {
  loading.value = true;
  getNetworkVersionList(queryParams.value).then(response => {
    dataList.value = response.data.rows?response.data.rows:[];
    total.value = response.data.total;
    loading.value = false;
  });
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  console.log(ids.value);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

// 上传
function handleUpload() {
  openDialog.value = true;
  form.value =  {

  };
  proxy.resetForm("uploadRef");
}

//保存工作空间文件发布服务
function fileSubmitForm() {
  const fileList = JSON.parse(
      JSON.stringify(proxy.$refs["fileUpload"].fileList)
  );
  console.log(fileList);
  let smwuCount = 0;
  let udbxCount = 0;
  let attachIdsArr = [];
  for (let i = 0; i < fileList.length; i++) {
    attachIdsArr.push(fileList[i].attachId);
    if(fileList[i].name.endsWith(".smwu")){
      smwuCount++;
    }else if(fileList[i].name.endsWith(".udbx")){
      udbxCount++;
    }
  }
  if(smwuCount==1 && udbxCount==1 && fileList.length==2){
    //成功上传1个.smwu文件和1个.udbx文件
    form.value.attachIds = attachIdsArr.join(",");
  }else{//清空
    form.value.attachIds = "";
  }
  if (activeName.value == "first") {
    form.value.type = "0";//国家级
  } else {
    form.value.type = "1";//省级
  }
  proxy.$refs["uploadRef"].validate(valid => {
    if (valid) {
      proxy.$modal.confirm('是否确认上传超图工作空间并发布道路网络分析服务？').then(function () {
        proxy.$modal.loading("正在发布，请稍候!");
        return newWorkspaceNetworkVersion(form.value);
      }).then(() => {
        proxy.$modal.closeLoading();
        proxy.$modal.alertSuccess("发布成功");
        form.value.fileList = [];
        openDialog.value = false;
        //查询数据列表
        getList();
      }).catch(() => {
        proxy.$modal.closeLoading();
        proxy.$modal.alertError("发布失败");
      });
    }
  });
}

//批量下载
function handleDownloads(){
  let idsArr = ids.value;
  let list = dataList.value;
  for(let i=0;i<idsArr.length;i++){
    for(let j=0;j<list.length;j++){
      if(list[j].id==idsArr[i]){
        handleDownloadsById(list[j]);
        break;
      }
    }
  }
}

//下载
function handleDownloadsById(row){
  let id = row.id;
  //下载文件
  let fileName = "超图工作空间数据编号" + row.version + ".zip";
  proxy.download("/hypergraph/downloadNetworkFileZip", {id:id}, fileName);
}

//批量删除
function handleDelete(){
  let idsStr = ids.value.join(",");
  proxy.$modal.confirm("是否确认批量删除所选数据？", 'Warning',{
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
  }).then(function () {
      proxy.$modal.loading("正在删除，请稍候!");
    return deleteNetworkanalystVersion({idsStr:idsStr});
  }).then(() => {
    proxy.$modal.closeLoading();
    proxy.$modal.alertSuccess("删除成功");
    //查询数据列表
    getList();
  }).catch(() => {
    proxy.$modal.closeLoading();
    proxy.$modal.alertError("删除失败");
  });
}

//删除
function handleDeleteById(id){
  proxy.$modal.confirm("是否确认删除此数据？", 'Warning',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(function () {
    proxy.$modal.loading("正在删除，请稍候!");
    return deleteNetworkanalystVersion({idsStr:id});
  }).then(() => {
    proxy.$modal.closeLoading();
    proxy.$modal.msgSuccess("删除成功");
    //查询数据列表
    getList();
  }).catch(() => {
    proxy.$modal.closeLoading();
    proxy.$modal.alertError("删除失败");
  });
}

//查看备注
function handleRemark(row){
  remarkForm.value = row;
  openRemark.value = true;
}

//下载帮助文档
function handleDownloadHelp(){
  importTemplate("道路数据转网络数据集方法.pdf");
}

// 模板下载
function importTemplate(name) {
  proxy.download("/fxfzaqbz/data/downloadExcel", {
    fileName: name
  }, name);
}

/** 获取省列表 */
function getProvinceData() {
  getProvince().then(response => {
    provinceData.value = response.data;
    provinceFormData.value = response.data;
    getPermissionData();
    //查询数据列表
    getList();
  });
}
function chooseProvince(value) {
  queryParams.value.cityId = null;
  queryParams.value.countyId = null;
  cityData.value = [];
  areaData.value = [];
  if(value!="全国"){
    getChildArea(value).then(response => {
      cityData.value = response.data;
    });
  }
}

function chooseCity(value) {
  queryParams.value.countyId = null;
  areaData.value = [];
  if(value!="全部"){
    getChildArea(value).then(response => {
      areaData.value = response.data;
    });
  }
}

function chooseFormProvince(value) {
  form.value.cityId = null;
  form.value.countyId = null;
  form.value.city = null;
  form.value.county = null;
  cityFormData.value = [];
  areaFormData.value = [];
  if(value!="全国"){
    getChildArea(value).then(response => {
      cityFormData.value = response.data;
    });
    //获取省名
    let provinceList = provinceFormData.value
    for(let i=0;i<provinceList.length;i++){
      if(provinceList[i].id==value){
        form.value.province = provinceList[i].name;
      }
    }
  }else{
    form.value.province = "全国";
  }
}

function chooseFormCity(value) {
  form.value.countyId = null;
  form.value.county = null;
  areaFormData.value = [];
  if(value!="全部"){
    getChildArea(value).then(response => {
      areaFormData.value = response.data;
    });
    //获取市名
    let cityList = cityFormData.value
    for(let i=0;i<cityList.length;i++){
      if(cityList[i].id==value){
        form.value.city = cityList[i].name;
      }
    }
  }else{
    form.value.city = null;
  }
}

function chooseFormArea(value) {
  if(value!="全部"){
    //获取区县名
    let countyList = areaFormData.value
    for(let i=0;i<countyList.length;i++){
      if(countyList[i].id==value){
        form.value.county = countyList[i].name;
      }
    }
  }else{
    form.value.county = null;
  }
  console.log(form.value)
}

// 获取登录人信息
function getPermissionData(){
  getPermission().then(res=>{
    isAdmin.value = res.data.isAdmin;
    // 如果是国家级人员
    if(isAdmin.value){
      queryParams.value.provinceId = '';
    }else{
      queryParams.value.provinceId = res.data.provinceId;
      //省份
      let provinceList = provinceData.value;
      for(let i=0;i<provinceList.length;i++){
        if(provinceList[i].id==res.data.provinceId){
          provinceData.value = [provinceList[i]];
          break;
        }
      }
      provinceFormData.value = provinceData.value;
    }
  });
}

getProvinceData();
</script>

<style lang="scss" scoped>
:deep(.el-link){
  --el-link-hover-text-color:red;
}
</style>
